package com.zhuxin.medical.mvc.controller;

import com.soecode.wxtools.api.WxConfig;
import com.soecode.wxtools.api.WxConsts;
import com.soecode.wxtools.api.WxMessageRouter;
import com.soecode.wxtools.api.WxService;
import com.soecode.wxtools.bean.*;
import com.soecode.wxtools.bean.result.KfAccountListResult;
import com.soecode.wxtools.util.xml.XStreamTransformer;
import com.zhuxin.events.AdminMsgHandler;
import com.zhuxin.events.EventHandle;
import com.zhuxin.events.SalerMsgHandler;
import com.zhuxin.medical.model.po.CommWxUser;
import com.zhuxin.medical.mvc.service.CommWxSerivce;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by lzb on 2018/11/13.
 */
@RestController
@RequestMapping("/wxinf")
public class WxMsg {

    public static ThreadLocal<CommWxUser> curruser=new ThreadLocal<>();

    @Autowired
    private WxService wxService;

    @Autowired
    private CommWxSerivce commWxSerivce;

    @Autowired
    private SalerMsgHandler salerMsgHandler;

    @Autowired
    private EventHandle eventHandle;

    @Autowired
    private AdminMsgHandler adminHandle;

    @GetMapping("/msg")
    @ResponseBody
    public String test(String signature,String timestamp,String nonce,String echostr ) {
        if (wxService.checkSignature(signature, timestamp, nonce, echostr)) {
            return echostr;
        }

        return null;
    }


    @PostMapping("/msg")
    @ResponseBody
    public String handleMsg(String signature, String timestamp, String nonce, String echostr , @RequestParam(required = false) String encrypt_type, String msg_signature, HttpServletRequest request) throws Exception {
        WxMessageRouter router = new WxMessageRouter(wxService);
        WxXmlMessage wx = null;
        wx=(encrypt_type != null && "aes".equals(encrypt_type))?WxXmlMessage.decryptMsg(request.getInputStream(), WxConfig.getInstance(), timestamp,nonce, msg_signature): XStreamTransformer.fromXml(WxXmlMessage.class, request.getInputStream());

        CommWxUser user=this.commWxSerivce.findUserById(wx.getFromUserName());
        if(user==null){//新用户
            WxUserList.WxUser wxUser=this.wxService.getUserInfoByOpenId(new WxUserList.WxUser.WxUserGet(wx.getFromUserName(),"ch"));
            user=new CommWxUser();
            user.setOpenid(wxUser.getOpenid());
            user.setNickname(wxUser.getNickname());
            user.setUsertype(0);
            this.commWxSerivce.saveUser(user);
        }
        WxMsg.curruser.set(user);
        if(user.getUsertype().intValue()==0){//普通用户
            router.rule().msgType("text").handler(salerMsgHandler).end();
        }else{//管理员
            router.rule().msgType("text").handler(adminHandle).end();
        }
        router.rule().msgType("event").handler(this.eventHandle).end();

        // 把消息传递给路由器进行处理
        WxXmlOutMessage xmlOutMsg = router.route(wx);
        if(xmlOutMsg==null)return null;



        return (encrypt_type != null && "aes".equals(encrypt_type))?WxXmlOutMessage.encryptMsg(WxConfig.getInstance(), xmlOutMsg.toXml(), timestamp, nonce):xmlOutMsg.toXml();
    }

    @RequestMapping("/getkf")
    @ResponseBody
    public String getkf() throws Exception {

//        String json="{\"kf_list\":[{\"kf_account\":\"kf2001@linyukeji007\",\"kf_headimgurl\":\"http:\\/\\/mmbiz.qpic.cn\\/mmbiz_jpg\\/5tMvPwGzKxZBgIIiansvRLR3X1JcQPeTAdUGCGcLqzjnd9PelAYEnIptZN4R9afChbf0RrOPRxKNqlO4zbfria2A\\/300?wx_fmt=jpeg\",\"kf_id\":2001,\"kf_nick\":\"佣金系统\",\"kf_wx\":\"lzblove\"}]}";
//        try {
//            KfAccountListResult.fromJson(json);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//
//        new KfAccountResult
        KfAccountListResult result = wxService.getAllKfAccount();
        return result.toString();
//        return null;
    }

    @RequestMapping("/sendmsg")
    @ResponseBody
    public String sendmsg() throws Exception {
        KfSender sender = new KfSender();
        sender.setTouser("oqcqkw8qmuLdS9qzm6p7oVhrIKPc");
        sender.setMsgtype(WxConsts.MASS_MSG_TEXT);
        sender.setText(new SenderContent.Text("hi"));
        sender.setCustomservice(new SenderContent.CustomService("kf2001@linyukeji007"));
        return wxService.sendMessageByKf(sender).toString();
    }

//    KfSender sender = new KfSender();
//sender.setTouser("oROCnuNihJnO9bnKOAORDFFriPgQ");
//sender.setMsgtype(WxConsts.MASS_MSG_TEXT);
//sender.setText(new Text("hi"));
//System.out.println(iService.sendMessageByKf(sender))


//    @RequestMapping("/addmenu")
//    @ResponseBody
//    public String addmenu() throws Exception {
//        WxMenu menu = this.wxService.getMenu().getMenu();
//        List<WxMenu.WxMenuButton> btnList = new ArrayList<>();
//
//        WxMenu.WxMenuButton btn2 = new WxMenu.WxMenuButton();
//        btn2.setType(WxConsts.BUTTON_CLICK);
//        btn2.setKey("zuofei");
//        btn2.setName("我要作废方案");
//
//        WxMenu.WxMenuButton btn1 = new WxMenu.WxMenuButton();
//        btn1.setType(WxConsts.BUTTON_CLICK);
//        btn1.setKey("list");
//        btn1.setName("待审批列表");
//
//
//        btnList.add(btn2);
//        btnList.add(btn1);
//        menu.setButton(btnList);
//        String rs=this.wxService.createMenu(menu, false);
//        System.out.println(rs);
//        System.out.println(this.wxService.getMenu().toJson());
//        return null;
//    }


}
